package demo3;

import java.lang.reflect.Array;
import java.util.Arrays;

public class MyArrayList implements IList {
    private int arr[];
    private int usedSize;
    private static final int DEFAULT_SIZE = 2;
    public MyArrayList() {
        arr = new int[DEFAULT_SIZE];
    }
    public MyArrayList(int size) {
        arr = new int[size];
    }
    @Override
    public void add(int data) {
        checkArrIsExpand();
        arr[usedSize++] = data;
    }
    //查看是否要扩容，如果要那么就扩大
    private void checkArrIsExpand() {
        if(isFull()) {
            arr = Arrays.copyOf(arr, 2 * arr.length);
        }
    }

    @Override
    public void add(int pos, int data) {
        try {
          checkPosOnAdd(pos);
        } catch (PosIllegal e) {
            e.printStackTrace();
            return;
        }
        checkArrIsExpand();
        for (int i = usedSize - 1; i >= pos; i--) {
            arr[i + 1] = arr[i];
        }
        arr[pos] = data;
        usedSize++;
    }
    //
    private void checkPosOnAdd(int pos) {
        if(pos < 0 || pos > usedSize) {
            System.out.println("输入坐标不合法！");
            throw new PosIllegal("该位置不合法 : pos = " + pos + " usedSize = " + usedSize);
        }
    }
    @Override
    public boolean contains(int toFind) {
        return indexOf(toFind) != -1;
    }

    @Override
    public int indexOf(int toFind) {
        for (int i = 0; i < usedSize; i++) {
            if(arr[i] == toFind) {
                return i;
            }
        }
        return -1;
    }
    private void checkPosOnGetAndSet(int pos) {
        if(pos < 0 || pos >= usedSize) {
            System.out.println("输入坐标不合法！");
            throw new PosIllegal("该位置不合法 : pos = " + pos + " usedSize = " + usedSize);
        }
    }
    @Override
    public int get(int pos) {
        checkPosOnGetAndSet(pos);
        return arr[pos];
    }

    @Override
    public void set(int pos, int value) {
        checkPosOnGetAndSet(pos);
        arr[pos] = value;
    }

    @Override
    public void remove(int toRemove) {
        int index = indexOf(toRemove);
        if(index == -1) {
            System.out.println("未找到该数字！");
            return;
        }
        for (int i = index; i < usedSize - 1; i++) {
            arr[i] = arr[i + 1];
        }
        usedSize--;
    }

    @Override
    public int size() {
        return usedSize;
    }

    @Override
    public void clear() {
        usedSize = 0;
    }

    @Override
    public void display() {
        for (int i = 0; i < usedSize; i++) {
            System.out.printf("%d ", arr[i]);
        }
        System.out.println();
    }
    @Override
    public boolean isFull() {
        return usedSize == arr.length;
    }
}
